package com.gin.kotlin.gf2gamecommunity.routes

import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Face
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.toRoute
import com.gin.kotlin.form.TopicPublishForm
import com.gin.kotlin.gf2gamecommunity.R
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.composable.DropdownMenuSelector
import com.gin.kotlin.gf2gamecommunity.base.composable.Loading
import com.gin.kotlin.gf2gamecommunity.base.composable.TabInfo
import com.gin.kotlin.gf2gamecommunity.base.composable.TabRowPager
import com.gin.kotlin.gf2gamecommunity.base.util.htmlLink
import com.gin.kotlin.gf2gamecommunity.base.util.insertBySelection
import com.gin.kotlin.gf2gamecommunity.callback.AbstractNothingCallback
import com.gin.kotlin.gf2gamecommunity.composable.HtmlText
import com.gin.kotlin.gf2gamecommunity.composable.ImageUploadIconButton
import com.gin.kotlin.gf2gamecommunity.viewmodel.CommunityIndexViewModel
import kotlinx.coroutines.delay
import kotlinx.serialization.Serializable


fun NavGraphBuilder.publish(onPopBackStack: () -> Unit) = composable<PublishRoute>(
    // 从屏幕右侧进入，持续500毫秒
    enterTransition = { slideInHorizontally(tween(500)) { it } },
    // 从屏幕右侧退出，持续500毫秒
    exitTransition = { slideOutHorizontally(tween(500)) { it } },
) {
    PublishComposable(route = it.toRoute(), onPopBackStack = onPopBackStack)
}

@Serializable
data class PublishRoute(val categoryId: Int)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun PublishComposable(
    route: PublishRoute,
    communityIndexViewModel: CommunityIndexViewModel = viewModel(),
    onPopBackStack: () -> Unit
) {
    // 版面ID
    var categoryId by remember { mutableIntStateOf(route.categoryId) }
    // 正文
    var textFieldValue by remember { mutableStateOf(TextFieldValue("")) }
    // 标题
    var title by remember { mutableStateOf("") }
    var showEmojiDialog by remember { mutableStateOf(false) }

    val categoryState = communityIndexViewModel.categories.fetch(false).observeAsState()
    val hotThemeState = communityIndexViewModel.hotThemes.fetch(false).observeAsState()

    Scaffold(
        topBar = {
            TopAppBar(navigationIcon = {
                IconButton(onClick = { onPopBackStack() }) {
                    Icon(imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "后退")
                }
            }, actions = {
                IconButton(
                    enabled = title.trim().isNotEmpty() && textFieldValue.toString().trim().isNotEmpty(),
                    onClick = {
                        App.INSTANCE.api.topicApi.publish(TopicPublishForm(
                            categoryId = categoryId,
                            title = title,
                            content = textFieldValue.text
                        )).enqueue(object : AbstractNothingCallback() {
                            override fun onSuccess(message: String) {
                                App.INSTANCE.replyFlag = true
                                // 回复成功退出界面
                                App.toast(message)
                                onPopBackStack()
                            }
                        })
                    }) {
                    Icon(painterResource(R.drawable.ic_send_24), contentDescription = "发送回复")
                }
            }, title = {
                Text("发布主题")
            })
        },

        ) { paddingValues ->
        Box(modifier = Modifier
            .padding(paddingValues)
            .fillMaxSize()) {
            Column(modifier = Modifier.padding(8.dp)) {
                // 选项
                Row(horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Text("版面: ")
                        categoryState.value?.also { list ->
                            DropdownMenuSelector(list = list.filter { it.canMove }, initValue = list.first { it.id == categoryId },
                                onSelected = { categoryId = it.id }) { it?.name ?: "未选择版面" }
                        } ?: Loading(modifier = Modifier)
                    }
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Text("话题: ")
                        // todo 多选话题
                    }
                }

                // 标题
                TextField(value = title, onValueChange = { title = it }, label = { Text("主题标题") }, modifier = Modifier.fillMaxWidth())

                val focusRequester = remember { FocusRequester() }
                // 使用 LaunchedEffect 在界面加载时请求焦点
                LaunchedEffect(Unit) {
                    // 延迟一小段时间以确保界面加载完成
                    delay(500)
                    focusRequester.requestFocus()
                }

                TabRowPager(listOf(
                    TabInfo("编辑") {
                        Column(modifier = Modifier.fillMaxSize()) {
                            TextField(value = textFieldValue, onValueChange = { textFieldValue = it }, label = { Text("主题正文") }, modifier = Modifier
                                .fillMaxWidth()
                                .focusRequester(focusRequester)
                                .weight(1f))

                            Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
                                ImageUploadIconButton { htmlImage, source ->
                                    val htmlLink = source?.let { "${htmlLink(it, "来源")}<br/><br/>$htmlImage" }
                                    textFieldValue = textFieldValue.insertBySelection(htmlLink ?: htmlImage)
                                }
                                IconButton(onClick = { showEmojiDialog = true }) {
                                    Icon(imageVector = Icons.Filled.Face, contentDescription = "插入表情")
                                }
                            }
                        }
                    },
                    TabInfo("预览") {
                        Column(modifier = Modifier.fillMaxWidth()) {
                            HtmlText(item = Unit, html = "<p>${textFieldValue.text}</p>")
                        }
                    },
                ))

            }

            if (showEmojiDialog) EmojiDialog(title = "选择表情", onDismissRequest = { showEmojiDialog = false }, onClickEmoji = { _, html ->
                textFieldValue = textFieldValue.insertBySelection(html)
            })
        }
    }
}